package com.mszl.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mszl.blog.dao.ArticleDao;
import com.mszl.blog.entity.Article;
import com.mszl.blog.service.ThreadService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service("threadService")

public class ThreadServiceImpl implements ThreadService {
    @Async("taskExecutor")
    @Override
    public void updateArticleViewCounts(ArticleDao articleDao, Article article) {
        int retryTimes=0;
        boolean updated=false;
        while(!updated&&retryTimes<5){
            Integer viewCounts=article.getViewCounts();
            Article articleupdate=new Article();
            articleupdate.setViewCounts(viewCounts+1);
            LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Article::getId, article.getId())
                    .eq(Article::getViewCounts, article.getViewCounts()) // CAS机制
                    .set(Article::getViewCounts, article.getViewCounts() + 1);



            int affect=articleDao.update(null,updateWrapper);//update article set veiw_counts ,WHERE id = 1 AND view_count =
            updated=affect>0;

            if(!updated){
                retryTimes++;
                article=articleDao.selectById(article.getId());
            }

        }
        if(!updated){
            System.out.println("false");
        }
        else {
            System.out.println("success");
        }
    }
}
